package com.zoe.onelink.business.mybatis.autoconfigure;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;

import java.util.List;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-10-26
 */
@MapperScan(basePackages = "com.zoe.onelink.business.dao")
public class MybatisBizAutoConfiguration {

    private static final List<String> BIZ_TYPE_ALIAS_PACKAGES = List.of(
            "com.zoe.onelink.business.entity",
            "com.zoe.onelink.business.cache.bean"
    );

    private final MybatisPlusProperties mybatisPlusProperties;

    public MybatisBizAutoConfiguration(MybatisPlusProperties mybatisPlusProperties) {
        this.mybatisPlusProperties = mybatisPlusProperties;
        this.setTypeAliasesPackage();
    }

    private void setTypeAliasesPackage() {
        String typeAliasesPackage = this.mybatisPlusProperties.getTypeAliasesPackage();
        String bizPackagesStr = StrUtil.join(StrUtil.COMMA, BIZ_TYPE_ALIAS_PACKAGES);
        if (StrUtil.isBlank(typeAliasesPackage)) {
            typeAliasesPackage = bizPackagesStr;
        } else {
            List<String> typePackages = StrUtil.split(typeAliasesPackage, StrUtil.COMMA);
            typePackages.addAll(BIZ_TYPE_ALIAS_PACKAGES);
            typeAliasesPackage = StrUtil.join(StrUtil.COMMA, CollUtil.distinct(typePackages));
        }
        this.mybatisPlusProperties.setTypeAliasesPackage(typeAliasesPackage);
    }


    @Bean
    @ConditionalOnProperty(name = "onelink.mybatis.plugins.map-key-underscore-to-camel-case", matchIfMissing = false)
    public ConfigurationCustomizer configurationCustomizer() {
        return i -> i.setObjectWrapperFactory(new MybatisMapWrapperFactory());
    }

}
